package com.tticar.invmanager.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.czy.tticar.dubbo.service.InvmanagerGoodsOrderService;
import com.invmanager.api.service.IDeliveryOrderForStaffClient;
import com.tticar.invmanager.common.exception.MyServiceException;
import com.tticar.invmanager.common.utils.BarcodeUtil;
import com.tticar.invmanager.common.utils.MyResponseBody;
import com.tticar.invmanager.common.utils.date.DateStyle;
import com.tticar.invmanager.common.utils.date.DateUtil;
import com.tticar.invmanager.entity.*;
import com.tticar.invmanager.entity.vo.*;
import com.tticar.invmanager.service.*;
import com.tticar.invmanager.tticar.entity.GoodsOrder;
import com.tticar.invmanager.tticar.entity.Store;
import com.tticar.invmanager.tticar.service.IGoodsOrderService;
import com.tticar.invmanager.tticar.service.IStoreService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.Format;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 采购单 前端控制器
 * </p>
 *
 * @author joeyYan
 * @since 2018-08-03
 */
@Controller
@RequestMapping("/pPurchase")
public class PPurchaseController extends BaseController {

    @Autowired
    private IPPurchaseService pPurchaseService;

    @Autowired
    private IWRelativeUnitService wRelativeUnitService;

    @Autowired
    private ISysDictService sysDictService;

    @Autowired
    private IWRelativeUnitService relativeUnitService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private IWWearhouseService wearhouseService;

    @Autowired
    private IMMaterielSkuService materielSkuService;


    @PostMapping
    @ResponseBody
    public MyResponseBody post(PPurchase pPurchase) {
        pPurchaseService.insertOrUpdate(pPurchase);
        return MyResponseBody.success();
    }

    @PostMapping("delete")
    @ResponseBody
    public MyResponseBody delete(@RequestParam("ids[]") List<Long> ids) {
        MyResponseBody responseBody = MyResponseBody.success();
        pPurchaseService.delete(ids);
        return responseBody;
    }

    @GetMapping("{id}")
    @ResponseBody
    public MyResponseBody get(@PathVariable("id") Long id) {
        MyResponseBody responseBody = MyResponseBody.success();
        responseBody.setData(pPurchaseService.selectById(id));
        return responseBody;
    }

    @GetMapping("edit")
    public String edit(PPurchase pPurchase, ModelMap modelMap) {
        modelMap.put("id", pPurchase.getId());
        return "/pPurchase/pPurchase_edit";
    }

    @PostMapping(value = "doEdit", produces="application/json;charset=UTF-8")
    @ResponseBody
    public MyResponseBody doEdit(PurchaseAddDto dto, String goods) throws ParseException {
        if (request.getSession().getAttribute("purchaseToken") == null ||
                !request.getSession().getAttribute("purchaseToken").toString().equals(dto.getToken())) {
            throw new MyServiceException("提交已受理，请勿重复提交");
        }
        request.getSession().removeAttribute("purchaseToken");
        MyResponseBody responseBody = MyResponseBody.success();
        List<PurchaseGoodsDto> goodsList = JSONArray.parseArray(goods, PurchaseGoodsDto.class);
        dto.setGoodsList(goodsList);
        pPurchaseService.addPurchase(dto);
        return responseBody;
    }

//    @GetMapping("detail")
//    public String detail(PPurchase pPurchase, ModelMap modelMap) {
//        modelMap.put("id", pPurchase.getId());
//        return "/pPurchase/pPurchase_detail";
//    }

    @GetMapping("list")
    @ResponseBody
    public Page list(PurchaseSearchDto searchDto, MyPage<PPurchase> page) {
        return pPurchaseService.search(searchDto, page);
    }

    @GetMapping
    public String index(Long relativeId, String searchText, ModelMap map) {
        if(relativeId != null && relativeId != 0) {
            map.put("relativeId", relativeId);
            WRelativeUnit unit = relativeUnitService.selectById(relativeId);
            map.put("relativeName", unit.getName());

            //本月
            map.put("startTime", DateUtil.getMonthFirstDay(new Date()));
            map.put("endTime", DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD));
        }
        if(StringUtils.isNotEmpty(searchText)) {
            map.put("searchText", searchText);
            //本月
            map.put("startTime", DateUtil.getMonthFirstDay(new Date()));
            map.put("endTime", DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD));
        }
        return "/pPurchase/pPurchase";
    }

    @RequestMapping("addPurchase")
    public String addPurchase(HttpServletRequest request, ModelMap modelMap) {
        long timeToken = System.currentTimeMillis();
        modelMap.put("addPurchaseToken", String.valueOf(timeToken));
        request.getSession().setAttribute("purchaseToken",String.valueOf(timeToken));
        return "/pPurchase/pPurchaseAdd";
    }

    @GetMapping("detail")
    public String detail(@RequestParam("purchaseId") long purchaseId, ModelMap modelMap) {
        modelMap.put("purchaseId", purchaseId);
        PPurchase purchase = this.pPurchaseService.selectById(purchaseId);
        modelMap.put("purchase", purchase);
        modelMap.put("ptime", DateUtil.DateToString(purchase.getPtime(), DateStyle.YYYY_MM_DD));
        modelMap.put("ctime", DateUtil.DateToString(purchase.getCtime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
        return "/pPurchase/pPurchase_detail";
    }

    /**
     * new version 窗口详情页
     * */
    @GetMapping("detailPage")
    public String detailPage(@RequestParam("purchaseId") Long purchaseId,ModelMap modelMap) {
        modelMap.put("purchaseId", purchaseId);
        PPurchase purchase = this.pPurchaseService.selectById(purchaseId);
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("id", purchase.getRelativeId());
        WRelativeUnit wRelativeUnit = wRelativeUnitService.selectOne(wrapper);
        if (wRelativeUnit != null) {
            modelMap.put("relative", wRelativeUnit.getName());
        }
        Wrapper wrapper1 = new EntityWrapper<>();
        wrapper1.eq("username", purchase.getUsername());
        SysUser sysUser = userService.selectOne(wrapper1);
        if (sysUser != null) {
            modelMap.put("username", sysUser.getNickname());
        }
        modelMap.put("purchase", purchase);
        if (purchase.getOrderStatus() == 0) {
            modelMap.put("otherMoney", 1);
        } else {
            modelMap.put("otherMoney", 0);
        }
        if (purchase.getOrderStatus() != 0 && purchase.getAmountIng().compareTo(BigDecimal.ZERO) > 0) {
            modelMap.put("endCount",1);
        }
        List<Map> purchaseTypes = sysDictService.selList(DictCodes.get("purchase_type"));
        for (int i = 0; i < purchaseTypes.size(); i++) {
            if (Integer.valueOf(purchaseTypes.get(i).get("value").toString()) == purchase.getPtype()) {
                modelMap.put("ptype", purchaseTypes.get(i).get("text"));
            }
        }
        if (purchase.getPayStatus() == 1) {
            modelMap.put("payStatus", "已结清");
        } else {
            modelMap.put("payStatus", "未结清");
        }
        if (purchase.getOrderStatus() == 0) {
            modelMap.put("orderStatus", "未入库");
        } else if (purchase.getOrderStatus() == 1) {
            modelMap.put("orderStatus", "已入库");
        } else {
            modelMap.put("orderStatus", "已完成");
        }
        //如果已经结清
        if (purchase.getPayStatus() == 1) {
            modelMap.put("endCount", 2);
            modelMap.put("otherMoney", 0);
        }

        modelMap.put("ptime", DateUtil.DateToString(purchase.getPtime(), DateStyle.YYYY_MM_DD));
        modelMap.put("ctime", DateUtil.DateToString(purchase.getCtime(), DateStyle.YYYY_MM_DD_HH_MM_SS));

        modelMap.put("totalMoney", purchase.getAmountActual().toString());
        modelMap.put("hasPay", purchase.getAmountAlready().toString());
        modelMap.put("amountIng", purchase.getAmountIng().toString());
        return "/pPurchase/new/purchaseDetailWindow";
    }

    @GetMapping("print")
    public String print(@RequestParam("purchaseId") long purchaseId, ModelMap modelMap) {
        modelMap.put("purchaseId", purchaseId);
        PPurchase purchase = this.pPurchaseService.selectById(purchaseId);
        modelMap.put("purchase", purchase);
        List<Map> purchaseType = sysDictService.selList(DictCodes.get("purchase_type"));
        for (int i = 0; i < purchaseType.size(); i++) {
            if (Integer.valueOf((String) purchaseType.get(i).get("value")).equals(purchase.getPtype())) ;
            modelMap.put("typeName",purchaseType.get(i).get("text"));
        }
        Wrapper wrapper = new EntityWrapper<>();
        List<WRelativeUnit> wRelativeUnits = wRelativeUnitService.selectList(wrapper);
        for (WRelativeUnit relative : wRelativeUnits) {
            if (relative.getId().equals(purchase.getRelativeId())) {
                modelMap.put("relativeName", relative.getName());
            }
        }
        Wrapper w = new EntityWrapper<>();
        w.eq("username", purchase.getUsername());
        SysUser sysUser = userService.selectOne(w);
        if (sysUser == null) {
            modelMap.put("buyMan", purchase.getUsername());
        } else {
            modelMap.put("buyMan", sysUser.getNickname());
        }

        modelMap.put("ptime", DateUtil.DateToString(purchase.getPtime(), DateStyle.YYYY_MM_DD));
        modelMap.put("ctime", DateUtil.DateToString(purchase.getCtime(), DateStyle.YYYY_MM_DD_HH_MM_SS));
        modelMap.put("thisTime", DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD));
        return "/pPurchase/pPurchase_print";
    }

    /**
     * 打印条码跳转页
     */
    @GetMapping("printBarCode")
    public String printBarCode(String wearhouseName,String positionName,String goodsName,String skus,String barCode,ModelMap modelMap) {
        //名称
        modelMap.put("wearhouseName", wearhouseName);
        modelMap.put("positionName", positionName);
        modelMap.put("goodsName", goodsName);
        modelMap.put("skus", skus);
        modelMap.put("barCodeSrc", "/pPurchase/purchaseBarCode?id=" + barCode);
        return "/pPurchase/pPurchase_printBarCode";
    }

    @PostMapping("detailList")
    @ResponseBody
    public List<Map> detailList(long purchaseId) {
        List<Map> purchaseDetailList = this.pPurchaseService.getPurchaseDetailList(purchaseId);
        List<Map> materiel_mu = sysDictService.selList(DictCodes.get("materiel_MU"));
        for (int i = 0; i < materiel_mu.size(); i++) {
            for (int j = 0; j < purchaseDetailList.size(); j++) {
                if (materiel_mu.get(i).get("value").equals(purchaseDetailList.get(j).get("unit"))) {
                    purchaseDetailList.get(j).put("unitName", materiel_mu.get(i).get("text"));
                }
            }

        }
        return purchaseDetailList;
    }

    @GetMapping("detailList")
    @ResponseBody
    public List<Map> detailListGet(Long purchaseId) {
        if (purchaseId == null) {
            return null;
        }
        List<Map> purchaseDetailList = this.pPurchaseService.getPurchaseDetailList(purchaseId);
        //仓库2位 + 分类序号4位 + 商品序号5位 + 供应商序号3位+采购日期6位  2019-1-15 14:12:43前
        // 商品序号5位 + 仓库2位 + 供应商序号3位+采购日期6位 2019-1-15 14:12:51后更改需求
        PPurchase purchase = this.pPurchaseService.selectById(purchaseId);
        Wrapper wrapper = new EntityWrapper<>();
        wrapper.eq("id", purchase.getRelativeId());
        wrapper.eq("rproperty", 2);
        WRelativeUnit wRelativeUnit = wRelativeUnitService.selectOne(wrapper);
        String relativeCode = wRelativeUnit.getCode();
        //供应商编码后3位
        relativeCode = relativeCode.substring(relativeCode.length() - 3, relativeCode.length());
        //单据日期后6位
        Format format = new SimpleDateFormat("yyMMdd");
        String orderDateCode = format.format(purchase.getPtime());

        for (int i =0; i<purchaseDetailList.size();i++) {
            purchaseDetailList.get(i).put("purchaseId", purchaseId);

            //2位仓库号
            Wrapper repositoryWrapper = new EntityWrapper<>();
            repositoryWrapper.eq("id", purchaseDetailList.get(i).get("wearhouseId"));
            WWearhouse wWearhouse = wearhouseService.selectOne(repositoryWrapper);
            String repositoryCode = wWearhouse.getCode();
            repositoryCode = repositoryCode.substring(repositoryCode.length() - 2, repositoryCode.length());

            //商品号后5位
            Wrapper skuWrapper = new EntityWrapper<>();
            skuWrapper.eq("id", purchaseDetailList.get(i).get("skuId"));
            MMaterielSku mMaterielSku = materielSkuService.selectOne(skuWrapper);
            String skuCode = mMaterielSku.getCode();
            skuCode = skuCode.substring(skuCode.length() - 5, skuCode.length());

//            Wrapper materielWrapper = new EntityWrapper<>();
//            materielWrapper.eq("id", mMaterielSku.getMid());
//            MMateriel mMateriel = materielService.selectOne(materielWrapper);
            //取后4位分类号
//            Wrapper categoryWrapper = new EntityWrapper<>();
//            categoryWrapper.eq("id", mMateriel.getCategoryId());
//            MCateogry mCateogry = categoryService.selectOne(categoryWrapper);
//            String categoryCode;
//            if (mCateogry != null) {
//                categoryCode = mCateogry.getCode();
//                categoryCode = categoryCode.substring(categoryCode.length() - 4, categoryCode.length());
//            } else {
//                categoryCode = "0000";
//            }


            //条形码码号
//            String barCode = repositoryCode + categoryCode + skuCode + relativeCode + orderDateCode;
            String barCode =  skuCode + repositoryCode + relativeCode + orderDateCode;
            purchaseDetailList.get(i).put("barCode", barCode);

        }
        return purchaseDetailList;
    }

    @GetMapping("purchaseBarCode")
    @ResponseBody
    public MyResponseBody purchaseBarCode(@RequestParam("id") String id,HttpServletResponse response) {
        MyResponseBody responseBody = MyResponseBody.success();
        byte[] barcode = BarcodeUtil.generateByte(id);
        ServletOutputStream out = null;
        try {
            out = response.getOutputStream();
            out.write(barcode);
            out.flush();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseBody;
    }


    @PostMapping("pay")
    @ResponseBody
    public MyResponseBody pay(Long purchaseId, BigDecimal payFee, Integer payType, String payRemark) {
        MyResponseBody responseBody = MyResponseBody.success();
        pPurchaseService.pay(purchaseId, payFee, payType, payRemark);
        return responseBody;
    }

    @PostMapping("inRepository")
    @ResponseBody
    public MyResponseBody inRepository(Long purchaseId) {
        MyResponseBody responseBody = MyResponseBody.success();
        pPurchaseService.inRepository(purchaseId);
        return responseBody;
    }
    /**
     * 窗口版入库，支持更改数量和实际进价
     * */
    @PostMapping("inRepositoryFromWindow")
    @ResponseBody
    public MyResponseBody inRepositoryFromWindow(Long purchaseId,String rows,BigDecimal realPay,BigDecimal totalMoney,
                                                 Integer payStatus,String remark) {
        if (realPay == null) {
            realPay = BigDecimal.ZERO;
        }
        MyResponseBody responseBody = MyResponseBody.success();
        List<PurchaseGoodsDto> goodsList = JSONArray.parseArray(rows, PurchaseGoodsDto.class);

        pPurchaseService.inRepositoryNewVersion(purchaseId,goodsList,realPay,totalMoney,payStatus,remark);
        return responseBody;
    }
    /**
     * 结算
     * */
    @PostMapping("endCountPurchase")
    @ResponseBody
    public MyResponseBody endCountPurchase(Long purchaseId,BigDecimal realPay,BigDecimal totalMoney,
                                                 Integer payStatus,String remark) {
        MyResponseBody responseBody = MyResponseBody.success();
        pPurchaseService.endCountPurchase(purchaseId,realPay,totalMoney,payStatus,remark);
        return responseBody;
    }

    /**
     * 撤销入库
     * */
    @PostMapping("cancelInPurchase")
    @ResponseBody
    public MyResponseBody cancelInPurchase(Long purchaseId) {
        MyResponseBody responseBody = MyResponseBody.success();
        pPurchaseService.cancelInPurchase(purchaseId);
        return responseBody;
    }

    /**
     * 撤销结算
     * */
    @PostMapping("cancelPurchaseEnd")
    @ResponseBody
    public MyResponseBody cancelPurchaseEnd(Long purchaseId) {
        MyResponseBody responseBody = MyResponseBody.success();
        pPurchaseService.cancelPurchaseEnd(purchaseId);
        return responseBody;
    }

    @Autowired
    private
    IDeliveryOrderForStaffClient deliveryOrderForStaffClient;
    @RequestMapping("test")
    @ResponseBody
    public MyResponseBody test(String orderId) {
        MyResponseBody responseBody = MyResponseBody.success();
        try {
            deliveryOrderForStaffClient.deliveryGoodsByStaffClient(orderId);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        return responseBody;
    }

}
